package com.ruoyi.car.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.student.service.ISysUserService;
import com.ruoyi.student.service.impl.SysRoleServiceImpl;
import com.ruoyi.car.domain.Passenger;
import com.ruoyi.car.mapper.PassengerMapper;
import com.ruoyi.car.service.IPassengerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 乘客信息Service业务层处理
 * 
 * @author xiaolin
 * @date 2025-01-21
 */
@Service
public class PassengerServiceImpl implements IPassengerService 
{
    @Autowired
    private PassengerMapper passengerMapper;
    @Autowired
    private TokenService tokenService;


    /**
     * 查询乘客信息
     * 
     * @param id 乘客信息主键
     * @return 乘客信息
     */
    @Override
    public Passenger selectPassengerById(Long id)
    {
        return passengerMapper.selectPassengerById(id);
    }

    /**
     * 查询乘客信息列表
     * 
     * @param passenger 乘客信息
     * @return 乘客信息
     */
    @Override
    public List<Passenger> selectPassengerList(Passenger passenger)
    {
        return passengerMapper.selectPassengerList(passenger);
    }

    /**
     * 新增乘客信息
     * 
     * @param passenger 乘客信息
     * @return 结果
     */
    @Override
    public int insertPassenger(Passenger passenger)
    {
        return passengerMapper.insertPassenger(passenger);
    }

    /**
     * 修改乘客信息
     * 
     * @param passenger 乘客信息
     * @return 结果
     */
    @Override
    public int updatePassenger(Passenger passenger)
    {
        return passengerMapper.updatePassenger(passenger);
    }

    /**
     * 批量删除乘客信息
     * 
     * @param ids 需要删除的乘客信息主键
     * @return 结果
     */
    @Override
    public int deletePassengerByIds(Long[] ids)
    {
        return passengerMapper.deletePassengerByIds(ids);
    }

    /**
     * 删除乘客信息信息
     * 
     * @param id 乘客信息主键
     * @return 结果
     */
    @Override
    public int deletePassengerById(Long id)
    {
        return passengerMapper.deletePassengerById(id);
    }
    /**
     * 微信小程序AppID
     */
    private final static String AppID = "wx72bb49c9120b9438";
    /**
     * 微信小程序AppSecret
     */
    private final static String AppSecret = "e997b805b2b4b29d4a7387ca3457f099";
    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysRoleServiceImpl sysRoleServiceImpl;
    @Override
    public AjaxResult wxlogin(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        String params = StrUtil.format("appid={}&secret={}&js_code={}&grant_type=authorization_code", AppID, AppSecret, code);
        String json = HttpUtils.sendGet(url,params);
        JSONObject jsonObject = JSONUtil.parseObj(json);
        String session_key = (String) jsonObject.get("session_key");
        String openid = (String) jsonObject.get("openid");
        if (StrUtil.isEmpty(openid))
        {
            return AjaxResult.error("未获取到openid");
        }
        Passenger passengerUser = passengerMapper.selectPassengerByOpenid(openid);
        Passenger passenger = new Passenger();
        if(passengerUser==null)
        {
            passenger.setOpenid(openid);
            System.out.println("DateUtils.getNowDate(): "+DateUtils.getNowDate());
            passenger.setCreatedAt(DateUtils.getNowDate());
            passenger.setSysUserId(1L);
            passengerMapper.insertPassenger(passenger);
        }
        else
        {
            passenger = passengerUser;
            passenger.setLoginTime(DateUtils.getNowDate());
            passengerMapper.updatePassenger(passenger);
        }
        SysUser sysUser = userService.selectUserById(passenger.getSysUserId());

        UserDetails userDetails = new LoginUser(sysUser.getUserId(), sysUser.getDeptId(), sysUser, sysRoleServiceImpl.selectRolePermissionByUserId(sysUser.getUserId()));

        Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails,null,AuthorityUtils.createAuthorityList("ROLE_USER"));

        SecurityContextHolder.getContext().setAuthentication(authentication);

        AsyncManager.me().execute(AsyncFactory.recordLogininfor(passenger.getUsername(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));

        String token = tokenService.createToken((LoginUser) authentication.getPrincipal());
        System.out.print("token  "+token);

        AjaxResult ajax = AjaxResult.success();
        ajax.put("token", token);
        ajax.put("userInfo", passenger);
        return ajax;
    }
}
